package com.xiaogang.minio.utils;

import cn.hutool.core.date.DateUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Date;

/**
 * @ProjectName : jiahua
 * @作者 : 侯小刚
 * @描述 : 操作文件的工具类
 * @创建日期 : 2022/12/23 11:29
 */
public class FileUtils {

    public static File getFile(String url) {
        //对本地文件命名
        String fileName = url.substring(url.lastIndexOf("."));
        fileName = dealFileName(fileName);
        File file = null;

        URL urlfile;
        InputStream inStream = null;
        OutputStream os = null;
        try {
            file = File.createTempFile("net_url", fileName);
            //下载
            urlfile = new URL(url);
            inStream = urlfile.openStream();
            os = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != inStream) {
                    inStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    /**
     * 处理Minio文件名
     * @param fileName
     * @return
     */
    public static String dealMinioFileName(String fileName) {
        // 时间戳转换为日期年月日时分秒
        String date = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        // 在文件名前面加上时间戳 + 随机数
        return "danduola/image/java/" + date +((int) (Math.random() * 100)) +'/' +fileName;
    }

    /**
     * 处理Minio文件名
     * @param fileName
     * @return
     */
    public static String dealFileName(String fileName) {
        // 时间戳转换为日期年月日时分秒
        String date = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        // 在文件名前面加上时间戳 + 随机数
        return date +((int) (Math.random() * 100)) +'_' +fileName;
    }
}
